package config

import (
	"os"
	"time"

	"github.com/pelletier/go-toml/v2"
)

type ServerConfig struct {
	Addr         string        `toml:"addr"`
	Mode         string        `toml:"mode"`
	ReadTimeout  time.Duration `toml:"read_timeout"`
	WriteTimeout time.Duration `toml:"write_timeout"`
	IdleTimeout  time.Duration `toml:"idle_timeout"`
}

type DatabaseConfig struct {
	Host         string `toml:"host"`
	Port         int    `toml:"port"`
	Username     string `toml:"username"`
	Password     string `toml:"password"`
	Database     string `toml:"database"`
	MaxIdleConns int    `toml:"max_idle_conns"`
	MaxOpenConns int    `toml:"max_open_conns"`
	MaxLifetime  int    `toml:"max_lifetime"`
}

type RedisConfig struct {
	Host     string `toml:"host"`
	Port     int    `toml:"port"`
	Password string `toml:"password"`
	Database int    `toml:"database"`
}

type LoggerConfig struct {
	Level string `toml:"level"`
}

type Config struct {
	Server   ServerConfig   `toml:"server"`
	Database DatabaseConfig `toml:"database"`
	Redis    RedisConfig    `toml:"redis"`
	Logger   LoggerConfig   `toml:"logger"`
}

var Instance *Config
var Redis *RedisConfig
var Database *DatabaseConfig
var Server *ServerConfig
var Logger *LoggerConfig

// Init 初始化配置
func Init(file string) error {
	Instance = &Config{}
	b, err := os.ReadFile(file)
	if err != nil {
		return err
	}
	if err := toml.Unmarshal(b, Instance); err != nil {
		return err
	}
	Redis = &Instance.Redis
	Database = &Instance.Database
	Server = &Instance.Server
	Logger = &Instance.Logger
	return nil
}

func GenerateConfig() string {
	config := &Config{
		Server: ServerConfig{
			Addr: ":8088",
			Mode: "debug",
		},
		Database: DatabaseConfig{
			Host:     "127.0.0.1",
			Port:     3306,
			Username: "root",
			Password: "root",
			Database: "test",
		},
		Redis: RedisConfig{
			Host:     "127.0.0.1",
			Port:     6379,
			Database: 0,
		},
		Logger: LoggerConfig{
			Level: "debug",
		},
	}
	data, _ := toml.Marshal(config)
	return string(data)
}
